<template>
    <div>
      <el-page-header @back="back()" content="达标优惠定制页面" style="margin-bottom: 10px;"/>
      <div class="full-minus">
        <span>达标优惠</span>
        <div class="row">
          <span class="span-style">活动编号：</span><span>{{id}}</span>
        </div>
        <el-tabs
          v-model="activeName"
          @tab-click="tabsHandleClick"
          style="width: 100%">
          <el-tab-pane label="基础配置" name="first">
            <div class="row">
              <span>目标群体:</span>
              <el-select v-model="targetGroup" placeholder="请选择">
                <el-option
                  v-for="item in targetGroupOptions"
                  :key="item.lv"
                  :label="item.name"
                  :value="item.lv">
                </el-option>
              </el-select>
            </div>
            <div class="row">
              <div class="block">
                <span class="span-style">活动时间：</span>
                <el-date-picker
                  v-model="dateRange"
                  type="datetimerange"
                  align="right"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  @change="setDate"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :default-time="['00:00:01', '23:59:59']">
                </el-date-picker>
              </div>
            </div>
          </el-tab-pane>

        <el-tab-pane label="主题配置" name="second">
          <span class="span-style">参与商品</span>
          <div class="row">
            <select-target-goods ref="targetGoods"></select-target-goods>
          </div>
        </el-tab-pane>

        <el-tab-pane label="活动配置" name="third">
          <div style="width: 100%;margin: 10px 0 0 0">
            <el-table
              :data="preferentialPlan"
              border
              max-height="250"
              style="width: 100%;display: block">
              <el-table-column
                label="达标金额">
                <template slot-scope="scope">
                  <template v-if="editState && scope.$index==planNum">
                    <el-input v-model="scope.row.condition"></el-input>
                  </template>
                  <template v-else>
                    <span class="span-style">{{scope.row.condition}}</span>
                  </template>
                </template>
              </el-table-column>
              <el-table-column
                label="方案类型">
                <template slot-scope="scope">
                  <span>{{scope.row.plan.str}}</span>
                </template>
              </el-table-column>
              <el-table-column
                label="方案内容">
                <template slot-scope="scope">
                  <template v-if="editState && scope.$index==planNum">
                    <template v-if="scope.row.plan.key==1">
                      <el-input v-model="scope.row.discount"></el-input>
                    </template>
                    <template v-else>
                      <el-select
                        v-model="scope.row.freeGoodsBarcode"
                        multiple placeholder="选择附赠商品"
                        value-key="barcode"
                        filterable
                        remote
                        reserve-keyword
                        :remote-method="selectFreeGoods"
                      >
                        <el-option
                          v-for="item in goodsList"
                          :key="item.barcode"
                          :label="item.name"
                          :value="item">
                          <span style="float: left">{{item.name}}</span>
                          <div @click.stop>
                            <el-input-number
                              style="float: right"
                              v-model="item.num"
                              size="mini">
                            </el-input-number>
                          </div>
                        </el-option>
                      </el-select>
                    </template>
                  </template>

                  <template v-else>
                    <span v-if="scope.row.plan.key==1">{{scope.row.discount}}</span>
                    <el-tag
                      v-for="tag in scope.row.freeGoodsBarcode"
                      :key="tag.barcode"
                      closable
                      @close="tagHandleClose(scope.$index,tag)"
                      :type="tag.type">
                      {{tag.name}}-{{tag.num}}
                    </el-tag>
                  </template>
                </template>
              </el-table-column>
              <el-table-column
                label="操作">
                <template slot-scope="scope">
                  <template v-if="scope.$index<planNum">
                    <el-button type="danger" @click="del(scope.$index)">删除</el-button>
                  </template>
                </template>
              </el-table-column>
            </el-table>
            <div class="btn-group" v-if="editState">
              <el-button type="primary" @click="save">确定</el-button>
              <el-button type="primary" @click="cancel">取消</el-button>
            </div>
            <div class="btn-group" v-else>
              <el-button type="primary" @click="cashDiscount">金额折扣</el-button>
              <el-button type="primary" @click="freeGoods">商品附赠</el-button>
            </div>
          </div>
        </el-tab-pane>
        </el-tabs>

        <div class="btn-group submit">
          <el-button type="primary" @click="submit">提交</el-button>
          <el-button type="primary" @click="exit">取消</el-button>
        </div>
      </div>
    </div>
</template>

<script>
    import SelectTargetGoods from "./SelectTargetGoods";
    export default {
        name: "FullMinus",
      components: {SelectTargetGoods},
      data(){
          return {
            //当前标签页
            activeName:'first',
            //活动编号
            id:this._func.getId(),
            //开始日期
            start:'',
            //结束日期
            end:'',
            //参与商品条码
            goodsBarcode:[],
            //目标群体
            targetGroup:0,
            //目标群体下拉框
            targetGroupOptions:[],

            dateRange:'',
            //优惠方案
            preferentialPlan:[],
            //状态
            editState:false,
            //附赠商品选择框
            goodsList: [],
            //方案数量
            planNum:0,

            fullMinus:[]
          }
      },
      mounted() {
        this.loadVIP();
      },
      methods:{
          back(){
            this.$router.back();
          },
          tabsHandleClick(tab,event){
          },
        //时间设置
        setDate(){
          this.end=this.dateRange[1];
          this.start=this.dateRange[0];
        },
          loadVIP(){
            this.$axios.get('VIP/info').then(resp=>{
              if(resp && resp.status==200){
                this.targetGroupOptions=resp.data;
              }
            })
          },
        //保存
        save(){
          //this.fullMinus=[];
          let row=this.preferentialPlan[this.preferentialPlan.length-1];
          let freeGoodsBarcode=[];
            if(row.plan==this._mytype.produce.FREEGOODS){
              freeGoodsBarcode=row.freeGoodsBarcode || [];
              if(freeGoodsBarcode.length==0){
                //如果无数据，则函数退出，并更新页面
                this.cancel();
                return;
              }
              let data=this._myobj.FullMinusList.createNew(this.id,
                row.condition,
                row.discount||0,
                [],
                this.preferentialPlan.length,
                this.preferentialPlan.length);

              freeGoodsBarcode.forEach((item,index)=>{
                data.freeGoodsList.push({
                  barcode:item.barcode,
                  num:item.num,
                  name:item.name
                })
              })
              this.fullMinus.push(data);
            }else if(row.plan==this._mytype.produce.CASHDISCOUNT){
              this.fullMinus.push(this._myobj.FullMinusList.createNew(
                this.id,
                row.condition,//达标金额
                row.discount || 0,//优惠金额
                [],
                this.preferentialPlan.length,
                this.preferentialPlan.length,
              ))
            }
            this.editState=false;

          this.planNum+=1;
          console.log(JSON.stringify(this.fullMinus));
        },
        //取消
        cancel(){
            console.log((JSON.stringify(this.editState)))
          this.editState=false;
          if(this.preferentialPlan.length>0){
            this.preferentialPlan.splice(this.preferentialPlan.length-1,1);
          }
        },
        //添加新行
        addNewRow(_plan){
          //if(!this.planEdit){
            this.preferentialPlan.push({
              id:this.id,
              condition:0,//达标金额
              discount:0 ,//优惠金额
              freeGoodsBarcode: [],//附赠商品
              //活动方案状态
              //planEdit:this._mytype.edit.NEW,
              plan:_plan,
              })
          //}
          console.log('addRow');
          console.log(JSON.stringify(this.preferentialPlan))
        },
        selectFreeGoods(query){
          this._post.selectGoodByQueryWithState(query,this._mytype.produceType.NULL).then(list=>{
            //console.log(JSON.stringify(list));
            if(list && list.length>0){
              list.forEach(item=>{
                let temp={
                  name:item.good.name,
                  barcode:item.good.barcode,
                  num:0,
                  condition:0,
                  discount:0
                }
                console.log(JSON.stringify(temp))
                this.goodsList.push(temp);
              })
            }
          })
        },
        //商品附赠
        freeGoods(){
            console.log(this.goodsList.length)
          console.log(JSON.stringify(this.goodList))
            //如果无数据，则请求

          if(this.goodsList.length==0){
          /*
            this._get.loadGoods(0).then(list=>{
              //console.log(JSON.stringify(list));
              list.forEach(item=>{
                let temp={
                  name:item.good.name,
                  barcode:item.good.barcode,
                  num:0,
                  condition:0,
                  discount:0
                }
                console.log(JSON.stringify(temp))
                this.goodsList.push(temp);
              })
            })

           */
          }
          //有数据则直接使用
          console.log(JSON.stringify(this.goodsList))
          this.addNewRow(this._mytype.produce.FREEGOODS);
          this.editState=true;
        },
        //现金折扣
        cashDiscount(){
            this.addNewRow(this._mytype.produce.CASHDISCOUNT);
            this.editState=true;
        },
        //移除标签
        tagHandleClose(index,tag){
            this.preferentialPlan[index].freeGoodsBarcode.splice(
              this.preferentialPlan[index].freeGoodsBarcode.indexOf(
                tag),1);
            if(this.preferentialPlan[index].freeGoodsBarcode.length==0){
              this.preferentialPlan.splice(index,1);
            }
        },
        //删除活动
        del(index){
          this.preferentialPlan.splice(index,1);
        },
        //活动提交
        submit(){
            let buffer=this.$refs.targetGoods.goodsBarcode;
            buffer.forEach(item=>{
              this.goodsBarcode.push({
                barcode:item,
                discount_id:this.id
              })
            })
          //对象封装
          let discountList=this._myobj.DiscountList.createNew(this.id,this.end,this.start,this.targetGroup);
          let fullMinus=this._myobj.FullMinusApply.createNew(
            discountList,
            this.fullMinus,
            this.goodsBarcode
          )
          /*
            let fullMinus={
            discountList:discountList,
            fullMinusList:this.fullMinus,
            discountGoodList:this.goodsBarcode
          }

           */
          console.log(JSON.stringify(fullMinus));
          //信息不完整
          if(fullMinus.discountList.end==null || fullMinus.discountGoodList==null || fullMinus.fullMinusList.length==0){
            this.$alert("活动信息不完整，请重新配置","通知",{
              confirmButtonText:'确定',
            });
          }else{
            this._post.submitFullMinus(fullMinus).then(resp=>{
              if(resp){
                this.$message({
                  message:'保存成功',
                  type:'success'
                });
              }
            })
            //页面跳转
            this.$router.push("./");
          }
        },
        //取消离开
        exit(){
            this.$router.push("./");
        },
      }
    }
</script>

<style scoped>
.full-minus{
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 75vw;
}
  .row{
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .span-style{
    white-space: nowrap;
  }
  btn-group{
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .submit{
    position: fixed;
    bottom: 10px;
  }
</style>
